import { NextResponse } from 'next/server';
import * as XLSX from 'xlsx';
import { prisma } from '@/lib/prisma';
import { format, parseISO } from 'date-fns';
import { zhCN } from 'date-fns/locale';

const expenseTypeMap = {
  material: '材料费',
  labor: '人工费',
  equipment: '设备费',
  other: '其他费用'
} as const;

const statusMap = {
  active: '进行中',
  completed: '已完工',
  paused: '已暂停'
} as const;

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const fromDate = searchParams.get('from') ? parseISO(searchParams.get('from')!) : undefined;
    const toDate = searchParams.get('to') ? parseISO(searchParams.get('to')!) : undefined;

    // 获取所有工地信息
    const sites = await prisma.site.findMany({
      include: {
        expenses: {
          where: {
            ...(fromDate && toDate
              ? {
                  paymentDate: {
                    gte: fromDate,
                    lte: toDate,
                  },
                }
              : {}),
          },
          select: {
            type: true,
            amount: true,
            paymentDate: true,
            vendor: true,
            description: true,
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    // 准备工作表数据
    const workbook = XLSX.utils.book_new();

    // 工地概览工作表
    const sitesOverview = sites.map(site => {
      const totalExpenses = site.expenses.reduce((sum, expense) => sum + expense.amount, 0);
      const expensesByType = site.expenses.reduce((acc, expense) => {
        acc[expense.type] = (acc[expense.type] || 0) + expense.amount;
        return acc;
      }, {} as Record<string, number>);

      return {
        '工地名称': site.name,
        '状态': statusMap[site.status],
        '合同金额': site.contractAmount,
        '已支出金额': totalExpenses,
        '剩余预算': site.contractAmount - totalExpenses,
        '材料费': expensesByType.material || 0,
        '人工费': expensesByType.labor || 0,
        '设备费': expensesByType.equipment || 0,
        '其他费用': expensesByType.other || 0,
        '创建时间': format(site.createdAt, 'yyyy年MM月dd日', { locale: zhCN }),
      };
    });

    const sitesSheet = XLSX.utils.json_to_sheet(sitesOverview);
    XLSX.utils.book_append_sheet(workbook, sitesSheet, '工地概览');

    // 支出明细工作表
    const expensesDetail = sites.flatMap(site => 
      site.expenses.map(expense => ({
        '工地名称': site.name,
        '支出类型': expenseTypeMap[expense.type],
        '支出金额': expense.amount,
        '支付日期': format(expense.paymentDate, 'yyyy年MM月dd日', { locale: zhCN }),
        '供应商': expense.vendor || '',
        '备注': expense.description || '',
      }))
    );

    const expensesSheet = XLSX.utils.json_to_sheet(expensesDetail);
    XLSX.utils.book_append_sheet(workbook, expensesSheet, '支出明细');

    // 按月统计工作表
    const monthlyStats = new Map<string, {
      total: number;
      material: number;
      labor: number;
      equipment: number;
      other: number;
    }>();

    sites.forEach(site => {
      site.expenses.forEach(expense => {
        const month = format(expense.paymentDate, 'yyyy年MM月', { locale: zhCN });
        const stats = monthlyStats.get(month) || {
          total: 0,
          material: 0,
          labor: 0,
          equipment: 0,
          other: 0,
        };
        stats.total += expense.amount;
        stats[expense.type] += expense.amount;
        monthlyStats.set(month, stats);
      });
    });

    const monthlyData = Array.from(monthlyStats.entries()).map(([month, stats]) => ({
      '月份': month,
      '总支出': stats.total,
      '材料费': stats.material,
      '人工费': stats.labor,
      '设备费': stats.equipment,
      '其他费用': stats.other,
    })).sort((a, b) => a['月份'].localeCompare(b['月份']));

    const monthlySheet = XLSX.utils.json_to_sheet(monthlyData);
    XLSX.utils.book_append_sheet(workbook, monthlySheet, '月度统计');

    // 生成Excel文件
    const buffer = XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' });

    // 设置响应头
    const headers = new Headers();
    headers.set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    const dateRange = fromDate && toDate
      ? `_${format(fromDate, 'yyyyMMdd')}-${format(toDate, 'yyyyMMdd')}`
      : `_${format(new Date(), 'yyyyMMdd')}`;
    headers.set('Content-Disposition', `attachment; filename="工程支出报表${dateRange}.xlsx"`);

    return new NextResponse(buffer, { headers });
  } catch (error) {
    console.error('导出报表失败:', error);
    return NextResponse.json({ error: '导出报表失败' }, { status: 500 });
  }
} 